package com.jerome.election.config;

import com.jerome.election.util.ReflectUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Responsible for processing the parameter information passed in by the main method
 */
public class ConfigUtil {
    /**
     * 匹配参数 {}
     */
    static Pattern pattern = Pattern.compile("((?<=\\{)([a-zA-Z_]+)(?=\\}))");
    /**
     * Convert args in main method to map
     * @param args
     * @return
     */
    public static Map<String,String> getMap(String[] args){
        Map<String, String> map = new HashMap<>();
        for (String arg : args) {
            String[] keyValue = arg.split("=", 2);
            if (keyValue.length < 2) {
                System.out.println("Invalid argument format: " + arg);
                continue;
            }
            String key = keyValue[0].trim();
            String value = keyValue[1].trim();
            map.put(key,value);
            System.out.println("Key: " + key + ", Value: " + value);
        }
        return map;
    }

    /**
     * properties Convert to corresponding entity object
     * @param properties
     * @param tClass
     * @param <T>
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <T> T build(Properties properties,Class<T> tClass) throws InstantiationException, IllegalAccessException {
        Map<String, String> map = new HashMap<>();
        for (String key : properties.stringPropertyNames()) {
            String value = properties.getProperty(key);
            map.put(key, value);
        }

        for (String key : properties.stringPropertyNames()) {
            String value = map.get(key);
            Matcher matcher = pattern.matcher(value);
            while (matcher.find()) {
                String find = matcher.group();
                if (map.keySet().contains(find)) {
                    value = value.replaceAll(String.format("\\{%s\\}",find),map.get(find));
                }
            }
            map.put(key,value);
        }
        return ReflectUtil.build(map,tClass);
    }

}
